﻿using System;
using System.Collections.Generic;
using System.Linq;
using Biz.EF.Platform;
using Hjt212Parser;
using log4net;

//using log4net;

namespace Biz.Buffer
{
    public static class CommonInformation
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(CommonInformation));
        private static int BufferTimespan = 10;

        private static List<EquipmentInfor> _letports;
        public static EquipmentInfor GetLetportByMn(string mn)
        {
            if (_letports == null || MyTimer.IsToTheTime("CommonInformation.GetLetportByMn", BufferTimespan))
            {
                using (var pCtx = new PlatformContext())
                {
                    _letports = pCtx.EquipmentInfors.AsNoTracking().ToList();
                }
            }
            var item = _letports.FirstOrDefault(t => t.企业端数采MN != null && t.企业端数采MN.Contains(mn));
            if (item == null)
            {
                item = _letports.FirstOrDefault(t => t.企业端数采二MN != null && t.企业端数采二MN.Contains(mn));
            }
            if (item == null)
            {
                item = _letports.FirstOrDefault(t => t.工控机编号MN != null && t.工控机编号MN.Contains(mn));
            }
            if (item == null)
            {
                Log.Error("MN号设置不正确，没有对应企业:" + mn);
            }
            return item;
        }
        public static DeviceType GetDeviceTypeByMn(string mn)
        {
            if (_letports == null || MyTimer.IsToTheTime("CommonInformation.GetDeviceTypeByMn", BufferTimespan))
            {
                using (var pCtx = new PlatformContext())
                {
                    _letports = pCtx.EquipmentInfors.AsNoTracking().ToList();
                }
            }
            var item = _letports?.FirstOrDefault(t => t.企业端数采MN != null && t.企业端数采MN.Contains(mn));
            if (item != null)
            {
                return DeviceType.Monitor;
            }
            item = _letports?.FirstOrDefault(t => t.企业端数采二MN != null && t.企业端数采二MN.Contains(mn));
            if (item != null)
            {
                return DeviceType.Monitor;
            }
            item = _letports?.FirstOrDefault(t => t.工控机编号MN != null && t.工控机编号MN.Contains(mn));
            if (item != null)
            {
                return DeviceType.Total;
            }
            return DeviceType.None;
        }
        public static EquipmentInfor GetLetportById(int id)
        {
            if (_letports == null || MyTimer.IsToTheTime("CommonInformation.GetLetportById", BufferTimespan))
            {
                using (var pCtx = new PlatformContext())
                {
                    _letports = pCtx.EquipmentInfors.AsNoTracking().ToList();
                }
            }
            return _letports?.FirstOrDefault(t => t.ID == id);
        }

        private static List<EnterpriseInfor> _pollutionSources;
        public static EnterpriseInfor GetPollutionSourceById(int id)
        {
            if (_pollutionSources == null || MyTimer.IsToTheTime("CommonInformation.GetPollutionSourceById", BufferTimespan))
            {
                using (var pCtx = new PlatformContext())
                {
                    _pollutionSources = pCtx.EnterpriseInfors.AsNoTracking().ToList();
                }
            }
            return _pollutionSources?.FirstOrDefault(t => t.ID == id);
        }

        private static int GetAreaIdByMn(string mn)
        {
            var port = GetLetportByMn(mn);
            if (port == null) return 1;
            if (_pollutionSources == null || MyTimer.IsToTheTime("CommonInformation.GetAreaIdByMn", BufferTimespan))
            {
                using (var pCtx = new PlatformContext())
                {
                    _pollutionSources = pCtx.EnterpriseInfors.AsNoTracking().ToList();
                }
            }
            var enterprise = _pollutionSources?.FirstOrDefault(t => t.ID == port.企业基本信息ID);
            if (enterprise == null) return 1;
            return enterprise.行政区编码ID;
        }

        private static List<MonitorFactorCode> _contamCodes;
        public static MonitorFactorCode GetContamCode(string code)
        {
            if (_contamCodes == null || MyTimer.IsToTheTime("CommonInformation.GetContamCode", BufferTimespan))
            {
                using (var pCtx = new PlatformContext())
                {
                    _contamCodes = pCtx.MonitorFactorCodes.AsNoTracking().ToList();
                }
            }
            return _contamCodes?.FirstOrDefault(t => t.污染物代码 != null && t.污染物代码.Trim().Equals(code.Trim()));
        }
        public static MonitorFactorCode GetFactorById(int id)
        {
            if (_contamCodes == null || MyTimer.IsToTheTime("CommonInformation.GetFactorById", BufferTimespan))
            {
                using (var pCtx = new PlatformContext())
                {
                    _contamCodes = pCtx.MonitorFactorCodes.AsNoTracking().ToList();
                }
            }
            return _contamCodes?.FirstOrDefault(t => t.ID == id);
        }

        private static List<SystemSetup> _systemSetups;
        public static SystemSetup GetSystemSetupByName(string name)
        {
            if (_systemSetups == null || MyTimer.IsToTheTime("CommonInformation.GetSystemSetupByName", BufferTimespan))
            {
                using (var pCtx = new PlatformContext())
                {
                    _systemSetups = pCtx.SystemSetups.AsNoTracking().ToList();
                }
            }
            return _systemSetups?.FirstOrDefault(t => t.参数名称 != null && t.参数名称.Contains(name));
        }
        /// <summary>
        /// 获取总量超量报警的发送次数
        /// </summary>
        /// <returns></returns>
        public static int GetMesssageSendTimes()
        {
            try
            {
                if (_systemSetups == null || MyTimer.IsToTheTime("CommonInformation.GetMesssageSendTimes", BufferTimespan))
                {
                    using (var pCtx = new PlatformContext())
                    {
                        _systemSetups = pCtx.SystemSetups.AsNoTracking().ToList();
                    }
                }
                var item = _systemSetups?.FirstOrDefault(t => t.参数名称 != null && t.参数名称.Contains("发送次数"));
                if (!string.IsNullOrEmpty(item?.参数内容))
                {
                    return int.Parse(item.参数内容.Trim());
                }
            }
            catch (Exception)
            {

            }
            return 3;
        }
        /// <summary>
        /// 获取总量统计报警类型：日、月、年；默认为月
        /// </summary>
        /// <returns></returns>
        private static string GetTotalAlarmUnit()
        {
            try
            {
                if (_systemSetups == null || MyTimer.IsToTheTime("CommonInformation.GetTotalAlarmUnit", BufferTimespan))
                {
                    using (var pCtx = new PlatformContext())
                    {
                        _systemSetups = pCtx.SystemSetups.AsNoTracking().ToList();
                    }
                }
                var item = _systemSetups?.FirstOrDefault(t => t.参数名称 != null && t.参数名称.Contains("总量统计报警类型"));
                if (!string.IsNullOrEmpty(item?.参数内容))
                {
                    return item.参数内容.Trim();
                }
            }
            catch (Exception)
            {

            }
            return "月";
        }

        private static List<阶梯收费标准> _chargings;
        public static 阶梯收费标准 GetCharging()
        {
            if (_chargings == null || MyTimer.IsToTheTime("CommonInformation.GetCharging", BufferTimespan))
            {
                using (var pCtx = new PlatformContext())
                {
                    _chargings = pCtx.阶梯收费标准.AsNoTracking().ToList();
                }
            }
            return _chargings?.FirstOrDefault();
        }

        private static List<设置浓度报警> _concentrationAlarmList;
        public static AlarmType GetConcentrationAlarm(string factorCode, double value)
        {
            if (_concentrationAlarmList == null || MyTimer.IsToTheTime("CommonInformation.GetConcentrationAlarm", BufferTimespan))
            {
                using (var pCtx = new PlatformContext())
                {
                    _concentrationAlarmList = pCtx.设置浓度报警.AsNoTracking().ToList();
                }
            }
            var item = _concentrationAlarmList.FirstOrDefault(t => t.污染物编码ID != null && t.MonitorFactorCode.污染物代码.Equals(factorCode));
            if (item?.预警值 == null || item.限制值 == null) return AlarmType.None;

            if (value > item.限制值.Value)
            {
                return AlarmType.ExceedLimit;
            }
            if (value > item.预警值.Value)
            {
                return AlarmType.ExceedEarlyWarningLessThanLimit;
            }
            return AlarmType.None;
        }
        public static 设置浓度报警 GetConcentrationValue(string factorCode)
        {
            if (_concentrationAlarmList == null || MyTimer.IsToTheTime("CommonInformation.GetConcentrationValue", BufferTimespan))
            {
                using (var pCtx = new PlatformContext())
                {
                    _concentrationAlarmList = pCtx.设置浓度报警.AsNoTracking().ToList();
                }
            }
            return _concentrationAlarmList.FirstOrDefault(t => t.污染物编码ID != null && t.MonitorFactorCode.污染物代码.Equals(factorCode));
        }

        private static List<设置排污量报警> _totalAlarmList;
        public static AlarmType GetTotalAlarm(string mn, double value)
        {
            if (_totalAlarmList == null || MyTimer.IsToTheTime("CommonInformation.GetTotalAlarm", BufferTimespan))
            {
                using (var pCtx = new PlatformContext())
                {
                    _totalAlarmList = pCtx.设置排污量报警.AsNoTracking().ToList();
                }
            }
            var type = GetTotalAlarmUnit();
            var port = GetLetportByMn(mn);
            if (port == null) return AlarmType.None;
            var item = _totalAlarmList.Where(t => t.类型.Contains(type)).FirstOrDefault(t => t.企业基本信息ID == port.企业基本信息ID);

            if (item?.预警量 == null || item.限制量 == null) return AlarmType.None;

            if (value > item.限制量.Value)
            {
                return AlarmType.ExceedLimit;
            }
            if (value > item.预警量.Value)
            {
                return AlarmType.ExceedEarlyWarningLessThanLimit;
            }
            return AlarmType.None;
        }
        public static 设置排污量报警 GetTotalValue(string mn)
        {
            if (_totalAlarmList == null || MyTimer.IsToTheTime("CommonInformation.GetTotalValue", BufferTimespan))
            {
                using (var pCtx = new PlatformContext())
                {
                    _totalAlarmList = pCtx.设置排污量报警.AsNoTracking().ToList();
                }
            }
            var type = GetTotalAlarmUnit();
            var port = GetLetportByMn(mn);
            if (port == null) return null;
            var item = _totalAlarmList.Where(t => t.类型.Contains(type)).FirstOrDefault(t => t.企业基本信息ID == port.企业基本信息ID);
            return item;
        }

        private static List<企业报警联系人> _enterpriseContacts;
        public static List<企业报警联系人> GetEnterpriseContacts(string mn)
        {
            var port = GetLetportByMn(mn);
            if (port == null) return null;
            if (_enterpriseContacts == null || MyTimer.IsToTheTime("CommonInformation.GetEnterpriseContacts", BufferTimespan))
            {
                using (var pCtx = new PlatformContext())
                {
                    _enterpriseContacts = pCtx.企业报警联系人.AsNoTracking().ToList();
                }
            }
            return _enterpriseContacts.Where(t => t.企业基本信息ID == port.企业基本信息ID).ToList();
        }

        private static List<报警联系人> _contacts;
        public static List<报警联系人> GetContacts(string mn)
        {
            var areaId = GetAreaIdByMn(mn);
            if (_contacts == null || MyTimer.IsToTheTime("CommonInformation.GetContacts", BufferTimespan))
            {
                using (var pCtx = new PlatformContext())
                {
                    _contacts = pCtx.报警联系人.AsNoTracking().ToList();
                }
            }
            return _contacts.Where(t => t.行政区ID == areaId).ToList();
        }

    }

    public enum DeviceType
    {
        Monitor,
        Total,
        None
    }

    public enum AlarmType
    {
        None,
        ExceedEarlyWarningLessThanLimit,
        ExceedLimit
    }
}
